﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;

namespace JwtAuthSample.Controllers
{
    //.net core推荐使用Claim授权
    //[Authorize(Roles ="user")] //基于角色授权,如果请求的token角色不对,会返回403
    [Authorize(Policy = "SuperAdminOnly")] //基于Claim的授权,自定义策略里定义了Claim必须包含SuperAdminOnly,如果不包含会返回403
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public async Task<int?> Get()
        {
            var auth = await HttpContext.AuthenticateAsync();//获取登录用户的AuthenticateResult
            if (auth.Succeeded)
            {
                var userCli = auth.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); //在声明集合中获取ClaimTypes.NameIdentifier 的值就是用户ID

                if (userCli == null || string.IsNullOrEmpty(userCli.Value))
                {
                    return null;
                }
                return Convert.ToInt32(userCli.Value);
            }


            return null;

        }


        [HttpPost]
        public async Task<List<string>> Post()
        {
            List<string> ClaimValList = new List<string>();

            var auth = await HttpContext.AuthenticateAsync();//获取登录用户的AuthenticateResult

            if (auth.Succeeded)
            {
                foreach (var item in auth.Principal.Claims)
                {
                    ClaimValList.Add($"{item.Type}:{item.Value}");
                }

                return ClaimValList;
            }

            return null;
        }
    }
}
